const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const { v4: uuidv4 } = require('uuid');
const db = require('./db');
const knative = require('./knative');

const app = express();
const PORT = process.env.PORT || 3002;

// Middleware
app.use(cors());
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '50mb' }));

// User registration endpoint
app.post('/api/register', async (req, res) => {
  const { username, password } = req.body;

  if (!username || !password) {
    return res.status(400).json({ error: '用户名和密码是必填项' });
  }

  try {
    if (db.useMemoryStorage) {
      // 检查用户是否已存在
      const existingUser = db.memoryStorage.users.find(user => user.username === username);
      
      if (existingUser) {
        return res.status(409).json({ error: '用户名已存在' });
      }
      
      const userId = uuidv4();
      db.memoryStorage.users.push({
        id: userId,
        username,
        password, // In production, this should be hashed
        created_at: new Date().toISOString()
      });
      
      res.status(201).json({ message: '用户注册成功', userId });
    } else {
      // 检查用户是否已存在
      const [existingUsers] = await db.execute(
        'SELECT id FROM users WHERE username = ?',
        [username]
      );

      if (existingUsers.length > 0) {
        return res.status(409).json({ error: '用户名已存在' });
      }

      const userId = uuidv4();
      await db.execute(
        'INSERT INTO users (id, username, password) VALUES (?, ?, ?)',
        [userId, username, password] // In production, this should be hashed
      );

      res.status(201).json({ message: '用户注册成功', userId });
    }
  } catch (error) {
    console.error('注册错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// User login endpoint
app.post('/api/login', async (req, res) => {
  const { username, password } = req.body;

  if (!username || !password) {
    return res.status(400).json({ error: '用户名和密码是必填项' });
  }

  try {
    if (db.useMemoryStorage) {
      const user = db.memoryStorage.users.find(u => u.username === username);
      
      if (!user || user.password !== password) { // In production, compare hashed passwords
        return res.status(401).json({ error: '用户名或密码错误' });
      }
      
      res.json({ message: '登录成功', userId: user.id, username: user.username });
    } else {
      const [users] = await db.execute(
        'SELECT id, username, password FROM users WHERE username = ?',
        [username]
      );

      if (users.length === 0 || users[0].password !== password) { // In production, compare hashed passwords
        return res.status(401).json({ error: '用户名或密码错误' });
      }

      const user = users[0];
      res.json({ message: '登录成功', userId: user.id, username: user.username });
    }
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// Create function endpoint
app.post('/api/functions', async (req, res) => {
  const { 
    name, 
    version, 
    description, 
    timeout, 
    handler, 
    image, 
    env, 
    limits, 
    requests,
    code,
    published = false
  } = req.body;

  if (!name || !image || !handler) {
    return res.status(400).json({ error: '函数名称、镜像和Handler是必填项' });
  }

  try {
    if (db.useMemoryStorage) {
      const functionId = uuidv4();
      const newFunction = {
        id: functionId,
        name,
        version: version || 'v1.0.0',
        description: description || '',
        timeout: timeout || 30,
        handler,
        image,
        env: JSON.stringify(env || {}),
        limits: JSON.stringify(limits || {}),
        requests: JSON.stringify(requests || {}),
        code: code || '',
        published: published || false,
        created_at: new Date().toISOString(),
        updated_at: new Date().toISOString()
      };
      
      db.memoryStorage.functions.push(newFunction);
      
      // 转换JSON字段
      const resultFunction = {
        ...newFunction,
        env: JSON.parse(newFunction.env),
        limits: JSON.parse(newFunction.limits),
        requests: JSON.parse(newFunction.requests)
      };
      
      res.status(201).json({ message: '函数创建成功', function: resultFunction });
    } else {
      const functionId = uuidv4();
      await db.execute(
        `INSERT INTO functions 
         (id, name, version, description, timeout, handler, image, env, limits, requests, code, published) 
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          functionId,
          name,
          version || 'v1.0.0',
          description || '',
          timeout || 30,
          handler,
          image,
          JSON.stringify(env || {}),
          JSON.stringify(limits || {}),
          JSON.stringify(requests || {}),
          code || '',
          published || false
        ]
      );

      // 获取刚创建的函数
      const [functions] = await db.execute(
        'SELECT * FROM functions WHERE id = ?',
        [functionId]
      );
      
      const newFunction = functions[0];
      // 转换JSON字段
      newFunction.env = JSON.parse(newFunction.env);
      newFunction.limits = JSON.parse(newFunction.limits);
      newFunction.requests = JSON.parse(newFunction.requests);
      
      res.status(201).json({ message: '函数创建成功', function: newFunction });
    }
  } catch (error) {
    console.error('创建函数错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// Get all functions
app.get('/api/functions', async (req, res) => {
  try {
    // 获取搜索关键词和是否只获取已发布的函数
    const searchKeyword = req.query.search;
    const publishedOnly = req.query.published === 'true';
    
    if (db.useMemoryStorage) {
      let functions = [...db.memoryStorage.functions];
      
      // 如果只获取已发布的函数
      if (publishedOnly) {
        functions = functions.filter(func => func.published);
      }
      
      // 如果有搜索关键词，过滤函数列表
      if (searchKeyword) {
        functions = functions.filter(func => 
          func.name.toLowerCase().includes(searchKeyword.toLowerCase()) ||
          (func.description && func.description.toLowerCase().includes(searchKeyword.toLowerCase())) ||
          func.handler.toLowerCase().includes(searchKeyword.toLowerCase())
        );
      }
      
      // 按创建时间倒序排列
      functions.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
      
      // 转换JSON字段
      const processedFunctions = functions.map(func => ({
        ...func,
        env: JSON.parse(func.env),
        limits: JSON.parse(func.limits),
        requests: JSON.parse(func.requests)
      }));
      
      res.json({ functions: processedFunctions });
    } else {
      let query = 'SELECT * FROM functions';
      let params = [];
      
      // 构建查询条件
      const conditions = [];
      
      // 如果只获取已发布的函数
      if (publishedOnly) {
        conditions.push('published = ?');
        params.push(true);
      }
      
      // 如果有搜索关键词，添加WHERE条件
      if (searchKeyword) {
        conditions.push('(name LIKE ? OR description LIKE ? OR handler LIKE ?)');
        const searchPattern = `%${searchKeyword}%`;
        params.push(searchPattern, searchPattern, searchPattern);
      }
      
      // 添加WHERE子句
      if (conditions.length > 0) {
        query += ' WHERE ' + conditions.join(' AND ');
      }
      
      query += ' ORDER BY created_at DESC';
      
      const [functions] = await db.execute(query, params);
      
      // 转换JSON字段
      const processedFunctions = functions.map(func => ({
        ...func,
        env: JSON.parse(func.env),
        limits: JSON.parse(func.limits),
        requests: JSON.parse(func.requests)
      }));
      
      res.json({ functions: processedFunctions });
    }
  } catch (error) {
    console.error('获取函数列表错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// Get function by ID
app.get('/api/functions/:id', async (req, res) => {
  try {
    if (db.useMemoryStorage) {
      const func = db.memoryStorage.functions.find(f => f.id === req.params.id);

      if (!func) {
        return res.status(404).json({ error: '函数不存在' });
      }

      // 转换JSON字段
      const resultFunction = {
        ...func,
        env: JSON.parse(func.env),
        limits: JSON.parse(func.limits),
        requests: JSON.parse(func.requests)
      };
      
      res.json({ function: resultFunction });
    } else {
      const [functions] = await db.execute(
        'SELECT * FROM functions WHERE id = ?',
        [req.params.id]
      );

      if (functions.length === 0) {
        return res.status(404).json({ error: '函数不存在' });
      }

      const func = functions[0];
      // 转换JSON字段
      func.env = JSON.parse(func.env);
      func.limits = JSON.parse(func.limits);
      func.requests = JSON.parse(func.requests);
      
      res.json({ function: func });
    }
  } catch (error) {
    console.error('获取函数错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// Update function
app.put('/api/functions/:id', async (req, res) => {
  try {
    if (db.useMemoryStorage) {
      const funcIndex = db.memoryStorage.functions.findIndex(f => f.id === req.params.id);

      if (funcIndex === -1) {
        return res.status(404).json({ error: '函数不存在' });
      }

      const { 
        name, 
        version, 
        description, 
        timeout, 
        handler, 
        image, 
        env, 
        limits, 
        requests,
        code
      } = req.body;

      const func = db.memoryStorage.functions[funcIndex];
      
      if (name !== undefined) func.name = name;
      if (version !== undefined) func.version = version;
      if (description !== undefined) func.description = description;
      if (timeout !== undefined) func.timeout = timeout;
      if (handler !== undefined) func.handler = handler;
      if (image !== undefined) func.image = image;
      if (env !== undefined) func.env = JSON.stringify(env);
      if (limits !== undefined) func.limits = JSON.stringify(limits);
      if (requests !== undefined) func.requests = JSON.stringify(requests);
      if (code !== undefined) func.code = code;
      
      func.updated_at = new Date().toISOString();

      // 转换JSON字段
      const resultFunction = {
        ...func,
        env: JSON.parse(func.env),
        limits: JSON.parse(func.limits),
        requests: JSON.parse(func.requests)
      };
      
      res.json({ message: '函数更新成功', function: resultFunction });
    } else {
      const [existingFunctions] = await db.execute(
        'SELECT id FROM functions WHERE id = ?',
        [req.params.id]
      );

      if (existingFunctions.length === 0) {
        return res.status(404).json({ error: '函数不存在' });
      }

      const { 
        name, 
        version, 
        description, 
        timeout, 
        handler, 
        image, 
        env, 
        limits, 
        requests,
        code
      } = req.body;

      // 构建更新语句
      let updateFields = [];
      let updateValues = [];
      
      if (name !== undefined) {
        updateFields.push('name = ?');
        updateValues.push(name);
      }
      
      if (version !== undefined) {
        updateFields.push('version = ?');
        updateValues.push(version);
      }
      
      if (description !== undefined) {
        updateFields.push('description = ?');
        updateValues.push(description);
      }
      
      if (timeout !== undefined) {
        updateFields.push('timeout = ?');
        updateValues.push(timeout);
      }
      
      if (handler !== undefined) {
        updateFields.push('handler = ?');
        updateValues.push(handler);
      }
      
      if (image !== undefined) {
        updateFields.push('image = ?');
        updateValues.push(image);
      }
      
      if (env !== undefined) {
        updateFields.push('env = ?');
        updateValues.push(JSON.stringify(env));
      }
      
      if (limits !== undefined) {
        updateFields.push('limits = ?');
        updateValues.push(JSON.stringify(limits));
      }
      
      if (requests !== undefined) {
        updateFields.push('requests = ?');
        updateValues.push(JSON.stringify(requests));
      }
      
      if (code !== undefined) {
        updateFields.push('code = ?');
        updateValues.push(code);
      }
      
      // 添加ID到值数组
      updateValues.push(req.params.id);
      
      if (updateFields.length > 0) {
        await db.execute(
          `UPDATE functions SET ${updateFields.join(', ')} WHERE id = ?`,
          updateValues
        );
      }

      // 获取更新后的函数
      const [functions] = await db.execute(
        'SELECT * FROM functions WHERE id = ?',
        [req.params.id]
      );
      
      const func = functions[0];
      // 转换JSON字段
      func.env = JSON.parse(func.env);
      func.limits = JSON.parse(func.limits);
      func.requests = JSON.parse(func.requests);
      
      res.json({ message: '函数更新成功', function: func });
    }
  } catch (error) {
    console.error('更新函数错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// Delete function
app.delete('/api/functions/:id', async (req, res) => {
  try {
    if (db.useMemoryStorage) {
      const funcIndex = db.memoryStorage.functions.findIndex(f => f.id === req.params.id);

      if (funcIndex === -1) {
        return res.status(404).json({ error: '函数不存在' });
      }

      db.memoryStorage.functions.splice(funcIndex, 1);
      res.json({ message: '函数删除成功' });
    } else {
      const [result] = await db.execute(
        'DELETE FROM functions WHERE id = ?',
        [req.params.id]
      );

      if (result.affectedRows === 0) {
        return res.status(404).json({ error: '函数不存在' });
      }

      res.json({ message: '函数删除成功' });
    }
  } catch (error) {
    console.error('删除函数错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// Deploy function to Knative (模拟部署)
app.post('/api/functions/:id/deploy', async (req, res) => {
  try {
    if (db.useMemoryStorage) {
      const func = db.memoryStorage.functions.find(f => f.id === req.params.id);

      if (!func) {
        return res.status(404).json({ error: '函数不存在' });
      }
      
      // 检查是否已经部署
      let instance = db.memoryStorage.instances.find(i => 
        i.function_id === func.id && i.status === 'Running'
      );

      if (instance) {
        // 更新现有实例
        instance.status = 'Running';
      } else {
        // 创建新实例
        const instanceId = uuidv4();
        const url = `http://${func.name}.default.example.com`;
        
        instance = {
          id: instanceId,
          function_id: func.id,
          status: 'Running',
          url,
          created_at: new Date().toISOString()
        };
        
        db.memoryStorage.instances.push(instance);
      }

      res.json({ 
        message: '函数部署成功', 
        instance 
      });
    } else {
      const [functions] = await db.execute(
        'SELECT id, name FROM functions WHERE id = ?',
        [req.params.id]
      );

      if (functions.length === 0) {
        return res.status(404).json({ error: '函数不存在' });
      }

      const func = functions[0];
      
      // 检查是否已经部署
      const [existingInstances] = await db.execute(
        'SELECT id FROM instances WHERE function_id = ? AND status = "Running"',
        [func.id]
      );

      let instance;
      if (existingInstances.length > 0) {
        // 更新现有实例
        const instanceId = existingInstances[0].id;
        await db.execute(
          'UPDATE instances SET status = "Running" WHERE id = ?',
          [instanceId]
        );
        
        const [instances] = await db.execute(
          'SELECT * FROM instances WHERE id = ?',
          [instanceId]
        );
        
        instance = instances[0];
      } else {
        // 创建新实例
        const instanceId = uuidv4();
        const url = `http://${func.name}.default.example.com`;
        
        await db.execute(
          'INSERT INTO instances (id, function_id, status, url) VALUES (?, ?, ?, ?)',
          [instanceId, func.id, 'Running', url]
        );
        
        const [instances] = await db.execute(
          'SELECT * FROM instances WHERE id = ?',
          [instanceId]
        );
        
        instance = instances[0];
      }

      res.json({ 
        message: '函数部署成功', 
        instance 
      });
    }
  } catch (error) {
    console.error('部署函数错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// Deploy function to real Knative platform
app.post('/api/functions/:id/deploy-real', async (req, res) => {
  try {
    // 获取函数信息
    let func;
    if (db.useMemoryStorage) {
      func = db.memoryStorage.functions.find(f => f.id === req.params.id);
      if (!func) {
        return res.status(404).json({ error: '函数不存在' });
      }
      
      // 解析JSON字段
      func = {
        ...func,
        env: JSON.parse(func.env),
        limits: JSON.parse(func.limits),
        requests: JSON.parse(func.requests)
      };
    } else {
      const [functions] = await db.execute(
        'SELECT * FROM functions WHERE id = ?',
        [req.params.id]
      );
      
      if (functions.length === 0) {
        return res.status(404).json({ error: '函数不存在' });
      }
      
      func = functions[0];
      // 解析JSON字段
      func.env = JSON.parse(func.env);
      func.limits = JSON.parse(func.limits);
      func.requests = JSON.parse(func.requests);
    }
    
    // 部署到Knative
    const deployResult = await knative.deployFunction(func);
    
    if (!deployResult.success) {
      return res.status(500).json({ 
        error: '部署到Knative失败', 
        details: deployResult.error 
      });
    }
    
    // 获取服务URL
    const serviceStatus = await knative.getServiceStatus(func.name);
    const serviceUrl = serviceStatus.url;
    
    // 更新或创建实例记录
    if (db.useMemoryStorage) {
      // 查找现有实例
      let instance = db.memoryStorage.instances.find(i => 
        i.function_id === func.id
      );
      
      if (instance) {
        // 更新现有实例
        instance.status = 'Running';
        instance.url = serviceUrl;
      } else {
        // 创建新实例
        const instanceId = uuidv4();
        instance = {
          id: instanceId,
          function_id: func.id,
          status: 'Running',
          url: serviceUrl,
          created_at: new Date().toISOString()
        };
        db.memoryStorage.instances.push(instance);
      }
      
      res.json({ 
        message: deployResult.message,
        instance,
        service: deployResult.service
      });
    } else {
      // 查找现有实例
      const [existingInstances] = await db.execute(
        'SELECT id FROM instances WHERE function_id = ?',
        [func.id]
      );
      
      if (existingInstances.length > 0) {
        // 更新现有实例
        await db.execute(
          'UPDATE instances SET status = ?, url = ? WHERE function_id = ?',
          ['Running', serviceUrl, func.id]
        );
        
        const [instances] = await db.execute(
          'SELECT * FROM instances WHERE function_id = ?',
          [func.id]
        );
        
        res.json({ 
          message: deployResult.message,
          instance: instances[0],
          service: deployResult.service
        });
      } else {
        // 创建新实例
        const instanceId = uuidv4();
        await db.execute(
          'INSERT INTO instances (id, function_id, status, url) VALUES (?, ?, ?, ?)',
          [instanceId, func.id, 'Running', serviceUrl]
        );
        
        const [instances] = await db.execute(
          'SELECT * FROM instances WHERE id = ?',
          [instanceId]
        );
        
        res.json({ 
          message: deployResult.message,
          instance: instances[0],
          service: deployResult.service
        });
      }
    }
  } catch (error) {
    console.error('部署函数到Knative错误:', error);
    res.status(500).json({ error: '服务器内部错误', details: error.message });
  }
});

// Get all instances
app.get('/api/instances', async (req, res) => {
  try {
    if (db.useMemoryStorage) {
      // 模拟JOIN操作
      const instances = db.memoryStorage.instances.map(instance => {
        const func = db.memoryStorage.functions.find(f => f.id === instance.function_id);
        return {
          ...instance,
          function_name: func ? func.name : null
        };
      }).sort((a, b) => new Date(b.created_at) - new Date(a.created_at)); // 按创建时间倒序排列
      
      res.json({ instances });
    } else {
      const [instances] = await db.execute(`
        SELECT i.*, f.name as function_name 
        FROM instances i 
        JOIN functions f ON i.function_id = f.id 
        ORDER BY i.created_at DESC
      `);
      
      res.json({ instances });
    }
  } catch (error) {
    console.error('获取实例列表错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// Get Knative instances status
app.get('/api/instances/knative-status', async (req, res) => {
  try {
    // 从Knative获取所有服务状态
    const knativeStatus = await knative.getAllServicesStatus();
    
    if (!knativeStatus.success) {
      return res.status(500).json({ 
        error: '获取Knative服务状态失败', 
        details: knativeStatus.error 
      });
    }
    
    res.json({ 
      message: '获取Knative服务状态成功',
      services: knativeStatus.services
    });
  } catch (error) {
    console.error('获取Knative实例状态错误:', error);
    res.status(500).json({ error: '服务器内部错误', details: error.message });
  }
});

// Get instance by ID
app.get('/api/instances/:id', async (req, res) => {
  try {
    if (db.useMemoryStorage) {
      const instance = db.memoryStorage.instances.find(i => i.id === req.params.id);

      if (!instance) {
        return res.status(404).json({ error: '实例不存在' });
      }

      const func = db.memoryStorage.functions.find(f => f.id === instance.function_id);
      const resultInstance = {
        ...instance,
        function_name: func ? func.name : null
      };
      
      res.json({ instance: resultInstance });
    } else {
      const [instances] = await db.execute(`
        SELECT i.*, f.name as function_name 
        FROM instances i 
        JOIN functions f ON i.function_id = f.id 
        WHERE i.id = ?
      `, [req.params.id]);

      if (instances.length === 0) {
        return res.status(404).json({ error: '实例不存在' });
      }

      res.json({ instance: instances[0] });
    }
  } catch (error) {
    console.error('获取实例错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// Get Knative service status by instance ID
app.get('/api/instances/:id/knative-status', async (req, res) => {
  try {
    // 首先获取实例信息
    let instance;
    let functionName;
    
    if (db.useMemoryStorage) {
      instance = db.memoryStorage.instances.find(i => i.id === req.params.id);
      if (!instance) {
        return res.status(404).json({ error: '实例不存在' });
      }
      
      const func = db.memoryStorage.functions.find(f => f.id === instance.function_id);
      if (!func) {
        return res.status(404).json({ error: '关联的函数不存在' });
      }
      
      functionName = func.name;
    } else {
      const [instances] = await db.execute(`
        SELECT i.*, f.name as function_name 
        FROM instances i 
        JOIN functions f ON i.function_id = f.id 
        WHERE i.id = ?
      `, [req.params.id]);

      if (instances.length === 0) {
        return res.status(404).json({ error: '实例不存在' });
      }
      
      instance = instances[0];
      functionName = instance.function_name;
    }
    
    // 从Knative获取服务状态
    const knativeStatus = await knative.getServiceStatus(functionName);
    
    if (!knativeStatus.success) {
      return res.status(500).json({ 
        error: '获取Knative服务状态失败', 
        details: knativeStatus.error 
      });
    }
    
    res.json({ 
      message: '获取Knative服务状态成功',
      service: knativeStatus
    });
  } catch (error) {
    console.error('获取Knative服务状态错误:', error);
    res.status(500).json({ error: '服务器内部错误', details: error.message });
  }
});

// Stop instance
app.post('/api/instances/:id/stop', async (req, res) => {
  try {
    if (db.useMemoryStorage) {
      const instance = db.memoryStorage.instances.find(i => i.id === req.params.id);

      if (!instance) {
        return res.status(404).json({ error: '实例不存在' });
      }

      instance.status = 'Stopped';
      res.json({ message: '实例停止成功', instance });
    } else {
      const [instances] = await db.execute(
        'SELECT id FROM instances WHERE id = ?',
        [req.params.id]
      );

      if (instances.length === 0) {
        return res.status(404).json({ error: '实例不存在' });
      }

      await db.execute(
        'UPDATE instances SET status = ? WHERE id = ?',
        ['Stopped', req.params.id]
      );
      
      const [updatedInstances] = await db.execute(
        'SELECT * FROM instances WHERE id = ?',
        [req.params.id]
      );
      
      const instance = updatedInstances[0];
      res.json({ message: '实例停止成功', instance });
    }
  } catch (error) {
    console.error('停止实例错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// Start instance
app.post('/api/instances/:id/start', async (req, res) => {
  try {
    if (db.useMemoryStorage) {
      const instance = db.memoryStorage.instances.find(i => i.id === req.params.id);

      if (!instance) {
        return res.status(404).json({ error: '实例不存在' });
      }

      instance.status = 'Running';
      res.json({ message: '实例启动成功', instance });
    } else {
      const [instances] = await db.execute(
        'SELECT id FROM instances WHERE id = ?',
        [req.params.id]
      );

      if (instances.length === 0) {
        return res.status(404).json({ error: '实例不存在' });
      }

      await db.execute(
        'UPDATE instances SET status = ? WHERE id = ?',
        ['Running', req.params.id]
      );
      
      const [updatedInstances] = await db.execute(
        'SELECT * FROM instances WHERE id = ?',
        [req.params.id]
      );
      
      const instance = updatedInstances[0];
      res.json({ message: '实例启动成功', instance });
    }
  } catch (error) {
    console.error('启动实例错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// Publish/Unpublish function
app.patch('/api/functions/:id/publish', async (req, res) => {
  try {
    const { published } = req.body;
    
    if (typeof published !== 'boolean') {
      return res.status(400).json({ error: 'published字段必须是布尔值' });
    }
    
    if (db.useMemoryStorage) {
      const funcIndex = db.memoryStorage.functions.findIndex(f => f.id === req.params.id);
      
      if (funcIndex === -1) {
        return res.status(404).json({ error: '函数不存在' });
      }
      
      db.memoryStorage.functions[funcIndex].published = published;
      db.memoryStorage.functions[funcIndex].updated_at = new Date().toISOString();
      
      const updatedFunction = {
        ...db.memoryStorage.functions[funcIndex],
        env: JSON.parse(db.memoryStorage.functions[funcIndex].env),
        limits: JSON.parse(db.memoryStorage.functions[funcIndex].limits),
        requests: JSON.parse(db.memoryStorage.functions[funcIndex].requests)
      };
      
      res.json({ 
        message: published ? '函数发布成功' : '函数撤回发布成功',
        function: updatedFunction 
      });
    } else {
      const [existingFunctions] = await db.execute(
        'SELECT id FROM functions WHERE id = ?',
        [req.params.id]
      );
      
      if (existingFunctions.length === 0) {
        return res.status(404).json({ error: '函数不存在' });
      }
      
      await db.execute(
        'UPDATE functions SET published = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
        [published, req.params.id]
      );
      
      // 获取更新后的函数
      const [functions] = await db.execute(
        'SELECT * FROM functions WHERE id = ?',
        [req.params.id]
      );
      
      const func = functions[0];
      // 转换JSON字段
      func.env = JSON.parse(func.env);
      func.limits = JSON.parse(func.limits);
      func.requests = JSON.parse(func.requests);
      
      res.json({ 
        message: published ? '函数发布成功' : '函数撤回发布成功',
        function: func 
      });
    }
  } catch (error) {
    console.error('发布/撤回发布函数错误:', error);
    res.status(500).json({ error: '服务器内部错误' });
  }
});

// Default route
app.get('/', (req, res) => {
  res.json({ message: 'serverless函数管理系统 API' });
});

// Start server
app.listen(PORT, async () => {
  console.log(`serverless函数管理系统后端服务监听端口 ${PORT}`);
  console.log(`当前数据库模式: ${db.useMemoryStorage ? '内存模式' : 'MySQL数据库模式'}`);
});